<template>
  <div class="product-review-container">
    <div class="page-header">
      <h2>产品评价</h2>
      <p>您可以对已完成的订单产品进行评价，分享您的使用体验</p>
    </div>
    
    <el-tabs v-model="activeTab" class="review-tabs">
      <el-tab-pane label="待评价" name="pending">
        <div class="empty-tip" v-if="pendingReviews.length === 0">
          <el-empty description="暂无待评价的产品" />
        </div>
        
        <div v-else class="review-list">
          <el-card v-for="item in pendingReviews" :key="item.id" class="review-card">
            <div class="product-info">
              <div class="product-image">
                <el-image :src="item.image" fit="cover" :preview-src-list="[item.image]" />
              </div>
              
              <div class="product-detail">
                <h3 class="product-name">{{ item.productName }}</h3>
                <p class="product-attributes">{{ item.attributes }}</p>
                <p class="order-info">订单编号：{{ item.orderNo }} | 完成时间：{{ item.completionTime }}</p>
              </div>
            </div>
            
            <el-divider />
            
            <el-button type="primary" size="large" @click="openReviewDialog(item)">
              立即评价
            </el-button>
          </el-card>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="已评价" name="reviewed">
        <div class="empty-tip" v-if="reviewedProducts.length === 0">
          <el-empty description="暂无已评价的产品" />
      </div>
      
        <div v-else class="review-list">
          <el-card v-for="item in reviewedProducts" :key="item.id" class="review-card">
        <div class="product-info">
              <div class="product-image">
                <el-image :src="item.image" fit="cover" :preview-src-list="[item.image]" />
              </div>
              
              <div class="product-detail">
                <h3 class="product-name">{{ item.productName }}</h3>
                <p class="product-attributes">{{ item.attributes }}</p>
                <p class="order-info">订单编号：{{ item.orderNo }} | 完成时间：{{ item.completionTime }}</p>
              </div>
            </div>
            
            <el-divider />
            
            <div class="review-detail">
              <div class="rating-area">
                <div class="rating-item">
                  <span class="rating-label">整体评分：</span>
                  <el-rate v-model="item.review.rating" disabled text-color="#ff9900" />
                </div>
                
                <div class="rating-item">
                  <span class="rating-label">材料质量：</span>
                  <el-rate v-model="item.review.materialRating" disabled text-color="#ff9900" />
                </div>
                
                <div class="rating-item">
                  <span class="rating-label">做工评分：</span>
                  <el-rate v-model="item.review.workmanshipRating" disabled text-color="#ff9900" />
                </div>
                
                <div class="rating-item">
                  <span class="rating-label">舒适度：</span>
                  <el-rate v-model="item.review.comfortRating" disabled text-color="#ff9900" />
                </div>
              </div>
              
              <div class="review-content">
                <div class="review-text">
                  <p><strong>评价内容：</strong>{{ item.review.content }}</p>
                </div>
                
                <div class="review-images" v-if="item.review.images && item.review.images.length > 0">
                  <p><strong>评价图片：</strong></p>
            <div class="image-list">
              <el-image 
                      v-for="(image, index) in item.review.images" 
                :key="index"
                :src="image"
                fit="cover"
                      style="width: 100px; height: 100px; margin-right: 10px;"
                      :preview-src-list="item.review.images"
                    />
                  </div>
                </div>
                
                <div class="review-time">
                  <p>评价时间：{{ item.review.reviewTime }}</p>
                </div>
                
                <div class="review-actions">
                  <el-button type="primary" plain size="small" @click="openUpdateDialog(item)">
                    修改评价
                  </el-button>
                  <el-button type="danger" plain size="small" @click="confirmDeleteReview(item.id)">
                    删除评价
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 评价表单对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      :title="isUpdate ? '修改产品评价' : '产品评价'"
      width="650px"
      destroy-on-close
    >
      <div v-if="currentProduct" class="review-form-container">
        <div class="product-info-mini">
          <el-image :src="currentProduct.image" fit="cover" style="width: 80px; height: 80px;" />
          <div class="product-info-detail">
            <h4>{{ currentProduct.productName }}</h4>
            <p>{{ currentProduct.attributes }}</p>
          </div>
        </div>
        
        <el-form 
          ref="reviewFormRef"
          :model="reviewForm"
          :rules="reviewRules"
          label-position="top"
        >
          <el-form-item label="整体评分" prop="rating">
            <el-rate v-model="reviewForm.rating" show-text :texts="ratingTexts" />
          </el-form-item>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="材料质量" prop="materialRating">
                <el-rate v-model="reviewForm.materialRating" />
          </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="做工评分" prop="workmanshipRating">
                <el-rate v-model="reviewForm.workmanshipRating" />
          </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="舒适度" prop="comfortRating">
                <el-rate v-model="reviewForm.comfortRating" />
          </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="评价内容" prop="content">
            <el-input 
              v-model="reviewForm.content"
              type="textarea" 
              :rows="4"
              placeholder="请分享您对产品的使用体验、优点和不足..."
            />
          </el-form-item>
          
          <el-form-item label="上传图片" class="upload-container">
            <el-upload
              v-model:file-list="reviewForm.fileList"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleImageChange"
              :limit="6"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="upload-tip">支持jpg、png格式，最多6张</div>
              </template>
            </el-upload>
          </el-form-item>
          
          <el-form-item label="是否匿名评价">
            <el-switch v-model="reviewForm.anonymous" />
            <span class="anonymous-tip">开启后，您的用户名将不会显示在评价中</span>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">提交评价</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 确认删除对话框 -->
    <el-dialog
      v-model="deleteConfirmVisible"
      title="确认删除"
      width="400px"
    >
      <p>确定要删除此评价吗？删除后无法恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteReview">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'ProductReview',
  components: {
    Plus
  },
  setup() {
    const activeTab = ref('pending')
    const pendingReviews = ref([])
    const reviewedProducts = ref([])
    const reviewDialogVisible = ref(false)
    const deleteConfirmVisible = ref(false)
    const reviewFormRef = ref(null)
    const currentProduct = ref(null)
    const isUpdate = ref(false)
    const deleteReviewId = ref(null)
    
    // 评分文字描述
    const ratingTexts = ['非常差', '差', '一般', '好', '非常好']
    
    // 评价表单数据
    const reviewForm = reactive({
      rating: 5,
      materialRating: 5,
      workmanshipRating: 5,
      comfortRating: 5,
      content: '',
      fileList: [],
      imageUrls: [],
      anonymous: false
    })
    
    // 表单验证规则
    const reviewRules = {
      rating: [
        { required: true, message: '请选择整体评分', trigger: 'change' }
      ],
      materialRating: [
        { required: true, message: '请选择材料质量评分', trigger: 'change' }
      ],
      workmanshipRating: [
        { required: true, message: '请选择做工评分', trigger: 'change' }
      ],
      comfortRating: [
        { required: true, message: '请选择舒适度评分', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入评价内容', trigger: 'blur' },
        { min: 10, max: 500, message: '评价内容在10-500字之间', trigger: 'blur' }
      ]
    }
    
    // 初始化数据
    onMounted(() => {
      // 在实际项目中应该从API获取数据
      loadPendingReviews()
      loadReviewedProducts()
    })
    
    // 加载待评价产品
    const loadPendingReviews = () => {
      // 模拟数据，实际项目中应该从API获取
      pendingReviews.value = [
        {
          id: 1,
          productName: '高级定制西装套装',
          attributes: '藏青色 | 羊毛混纺 | 修身版型',
          image: 'https://picsum.photos/id/1011/300/300',
          orderNo: 'ORD20230315001',
          completionTime: '2023-03-15'
        },
        {
          id: 2,
          productName: '商务正装衬衫',
          attributes: '白色 | 100%纯棉 | 修身版型',
          image: 'https://picsum.photos/id/1016/300/300',
          orderNo: 'ORD20230320002',
          completionTime: '2023-03-20'
        }
      ]
    }
    
    // 加载已评价产品
    const loadReviewedProducts = () => {
      // 模拟数据，实际项目中应该从API获取
      reviewedProducts.value = [
        {
          id: 3,
          productName: '职业工装套装',
          attributes: '灰色 | 精选混纺 | 标准版型',
          image: 'https://picsum.photos/id/1025/300/300',
          orderNo: 'ORD20230215003',
          completionTime: '2023-02-15',
          review: {
            rating: 4.5,
            materialRating: 4,
            workmanshipRating: 5,
            comfortRating: 4.5,
            content: '面料很舒适，穿着非常合身，做工精细。唯一的小缺点是领口有点偏紧，其他方面都很满意。总体来说是一次很好的定制体验。',
            images: [
              'https://picsum.photos/id/1059/300/300',
              'https://picsum.photos/id/1060/300/300'
            ],
            reviewTime: '2023-02-20'
          }
        },
        {
          id: 4,
          productName: '商务休闲裤',
          attributes: '卡其色 | 棉质 | 直筒版型',
          image: 'https://picsum.photos/id/1082/300/300',
          orderNo: 'ORD20230110004',
          completionTime: '2023-01-10',
          review: {
            rating: 5,
            materialRating: 5,
            workmanshipRating: 5,
            comfortRating: 5,
            content: '这条裤子简直太棒了！面料很柔软舒适，穿着很合身，尺寸完美。做工非常精细，细节处理得很好。洗过几次依然保持形状和颜色。强烈推荐给需要商务休闲裤的朋友们！',
            images: [
              'https://picsum.photos/id/1071/300/300'
            ],
            reviewTime: '2023-01-15'
          }
        }
      ]
    }
    
    // 打开评价对话框
    const openReviewDialog = (product) => {
      currentProduct.value = product
      isUpdate.value = false
      
      // 重置表单
      Object.assign(reviewForm, {
        rating: 5,
        materialRating: 5,
        workmanshipRating: 5,
        comfortRating: 5,
        content: '',
        fileList: [],
        imageUrls: [],
        anonymous: false
      })
      
      reviewDialogVisible.value = true
    }
    
    // 打开修改评价对话框
    const openUpdateDialog = (product) => {
      currentProduct.value = product
      isUpdate.value = true
      
      // 填充表单数据
      Object.assign(reviewForm, {
        rating: product.review.rating,
        materialRating: product.review.materialRating,
        workmanshipRating: product.review.workmanshipRating,
        comfortRating: product.review.comfortRating,
        content: product.review.content,
        fileList: product.review.images.map((url, index) => ({
          name: `image${index + 1}.jpg`,
          url
        })),
        imageUrls: [...product.review.images],
        anonymous: false // 假设匿名状态无法获取
      })
      
      reviewDialogVisible.value = true
    }
    
    // 处理图片上传
    const handleImageChange = (file, fileList) => {
      reviewForm.fileList = fileList
      
      if (file.raw) {
          const reader = new FileReader()
        reader.readAsDataURL(file.raw)
          reader.onload = () => {
          // 在实际项目中，这里应该上传图片到服务器
          // 此处仅为演示，将图片转为 base64 直接保存
          if (!reviewForm.imageUrls.includes(reader.result)) {
            reviewForm.imageUrls.push(reader.result)
          }
        }
      }
    }
    
    // 提交评价
    const submitReview = async () => {
      if (!reviewFormRef.value) return
      
      const valid = await reviewFormRef.value.validate().catch(() => false)
      if (!valid) {
        ElMessage.error('请完成表单填写')
        return
      }
      
      // 构建评价数据
      const reviewData = {
        productId: currentProduct.value.id,
        rating: reviewForm.rating,
        materialRating: reviewForm.materialRating,
        workmanshipRating: reviewForm.workmanshipRating,
        comfortRating: reviewForm.comfortRating,
        content: reviewForm.content,
        images: reviewForm.imageUrls,
        anonymous: reviewForm.anonymous
      }
      
      // 在实际项目中，这里应该调用API提交评价
      console.log('提交评价数据:', reviewData)
      
      if (isUpdate.value) {
        // 更新现有评价
        const index = reviewedProducts.value.findIndex(p => p.id === currentProduct.value.id)
        if (index !== -1) {
          reviewedProducts.value[index].review = {
            ...reviewData,
            reviewTime: new Date().toLocaleDateString('zh-CN')
          }
          ElMessage.success('评价更新成功')
        }
      } else {
        // 添加新评价
        const newReview = {
          ...currentProduct.value,
          review: {
            ...reviewData,
            reviewTime: new Date().toLocaleDateString('zh-CN')
          }
        }
        reviewedProducts.value.unshift(newReview)
        
        // 从待评价列表中移除
        pendingReviews.value = pendingReviews.value.filter(p => p.id !== currentProduct.value.id)
        
        ElMessage.success('评价提交成功')
      }
      
      reviewDialogVisible.value = false
      
      // 确保显示已评价标签页
      activeTab.value = 'reviewed'
    }
    
    // 确认删除评价
    const confirmDeleteReview = (reviewId) => {
      deleteReviewId.value = reviewId
      deleteConfirmVisible.value = true
    }
    
    // 删除评价
    const deleteReview = () => {
      if (!deleteReviewId.value) return
      
      // 在实际项目中，这里应该调用API删除评价
      
      // 从已评价列表中移除
      const index = reviewedProducts.value.findIndex(p => p.id === deleteReviewId.value)
      if (index !== -1) {
        const deletedProduct = reviewedProducts.value.splice(index, 1)[0]
        
        // 将产品添加回待评价列表
        const productWithoutReview = {
          id: deletedProduct.id,
          productName: deletedProduct.productName,
          attributes: deletedProduct.attributes,
          image: deletedProduct.image,
          orderNo: deletedProduct.orderNo,
          completionTime: deletedProduct.completionTime
        }
        pendingReviews.value.push(productWithoutReview)
      }
      
      deleteConfirmVisible.value = false
      deleteReviewId.value = null
      
      ElMessage.success('评价已删除')
    }
    
    return {
      activeTab,
      pendingReviews,
      reviewedProducts,
      reviewDialogVisible,
      deleteConfirmVisible,
      reviewFormRef,
      currentProduct,
      isUpdate,
      reviewForm,
      reviewRules,
      ratingTexts,
      openReviewDialog,
      openUpdateDialog,
      handleImageChange,
      submitReview,
      confirmDeleteReview,
      deleteReview
    }
  }
}
</script>

<style scoped>
.product-review-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 14px;
}

.review-tabs {
  margin-bottom: 20px;
}

.empty-tip {
  padding: 30px 0;
}

.review-list {
  margin-top: 20px;
}

.review-card {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  margin-bottom: 15px;
}

.product-image {
  width: 120px;
  height: 120px;
  margin-right: 20px;
  flex-shrink: 0;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.product-detail {
  flex: 1;
}

.product-name {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: 500;
}

.product-attributes {
  color: #606266;
  margin-bottom: 10px;
}

.order-info {
  color: #909399;
  font-size: 13px;
}

.review-detail {
  display: flex;
  flex-direction: column;
  padding-top: 10px;
}

.rating-area {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.rating-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
  margin-bottom: 10px;
}

.rating-label {
  margin-right: 8px;
  white-space: nowrap;
}

.review-content {
  padding: 10px 0;
}

.review-text {
  margin-bottom: 15px;
  line-height: 1.6;
}

.review-images {
  margin-bottom: 15px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.review-time {
  color: #909399;
  font-size: 13px;
  margin-bottom: 15px;
}

.review-actions {
  display: flex;
  gap: 10px;
}

.product-info-mini {
  display: flex;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.product-info-detail {
  margin-left: 15px;
}

.product-info-detail h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.product-info-detail p {
  margin: 0;
  color: #606266;
  font-size: 13px;
}

.upload-container {
  margin-top: 10px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.anonymous-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}
</style> 